import traceback
import json
from datetime import datetime
from flask import Blueprint, request, abort
from flask_restful import reqparse, inputs, Resource, Api, fields, marshal_with
from ..res import output_json
from ...libs.unit import formatDate, vail_pwd, make_crypt, make_pwd, abort_msg,make_token
from ...models.database import db
from ...models.console.admin import Admin
from ...decorator.consolejwt import console_token
from ...redis import rd
from ...models.console.roleuser import RoleUser
from ...models.console.rolepriv import RolePriv
from ...models.console.menu import Menu

# 蓝图并放入 restful
login = Blueprint('login', __name__, url_prefix='/c-api/login')
api = Api(login)

# 统一封装 API 返回值
@api.representation('application/json')
def out_json(data, code, headers=None):
    return output_json(data, code, headers=None)


# 封装返回的数据格式
resource_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'token': fields.String
}
class Login(Resource):
    @console_token
    @marshal_with(resource_fields, envelope='resource')
    def post(self):
        # 请求验证
        parser = reqparse.RequestParser()
        parser.add_argument('admin_name', type=str,
                            help='登录名必须填写', location=['form', 'args'], required=True, action='store')
        parser.add_argument('admin_pwd', type=vail_pwd,
                            location=['form', 'args'], required=True, action='store')
        args = parser.parse_args()
        a_name = args.get('admin_name')
        a_pwd = args.get('admin_pwd')
        c = Admin.query.filter(Admin.name == a_name).one()
        if make_pwd(a_pwd,c.crypt) != c.password:
            abort(401,'密码错误')
        # 找出所有权限放入 Redis
        rids = RoleUser.query.filter(RoleUser.user_id == c.id).with_entities(RoleUser.role_id).distinct().all()
        allrids = [n[0] for n in rids]
        privs = RolePriv.query.filter(RolePriv.role_id.in_(
            allrids)).with_entities(RolePriv.label,RolePriv.name).distinct().all()
        # 超级管理员权限
        if c.id == 1:
            allrids = [1]
            privs = Menu.query.with_entities(Menu.label, Menu.name).distinct().all()
        allpriv = {i[0]:i[1] for i in privs}
        # 生成 token
        token = make_token(c.id,c.name)
        # 删除指定前缀的
        # rd.delete(*rd.keys(pattern='c-token:*'))
        rdstr = json.dumps({'id': c.id, 'name': c.name, 'allRole': allrids, 'allPriv': allpriv})
        rd.set('c-token:' + token, rdstr, ex = 3600 * 24)
        return {'id':c.id, 'name': c.name, 'token': token}

api.add_resource(Login, '/')
